package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.service.WxLoginService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.*;

import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * wx 登录
 */

@RestController
@RequestMapping("/wx/unauth")
public class SystemWXController {
    @Autowired
    private WxLoginService wxLoginService;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private SysLoginService loginService;

    private boolean showCode;


    private String captchaType;

    public static String getRandomString(Integer num) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

//    @PostMapping("/code")
//    @ApiOperation("用户登录接口")
//    @CachePut
//    public AjaxResult ajaxLogin(String code, HttpServletRequest request) {
//        String result = wxLoginService.sendResponseH5(code);
//        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
//        String accessToken = jsonObject.getString("access_token");
//        String openId = jsonObject.getString("openid");
////        String openId = jsonObject.getString("errcode");
//        WxLogin wxLogin = new WxLogin();
//        wxLogin.setOpenId(openId);
//        wxLogin.setLoginDate(new Date());
//        if (openId != null) {
//            // 根据openId查找用户
//            WxLogin userOptional = wxLoginService.selectWxLogin(openId);
//            if (userOptional != null) {
//                // 如果已经存在，直接登录后返回
//                Long userId = userOptional.getUserId();
//                SysUser user = userOptional.getUsers();
//                // 生成一个jsonId
//                String jsonId = CharUtil.getRandomString(32);
//                Map<String, Object> map = new HashMap<>();
//                map.put("user", user);
//                map.put("jsonId", jsonId);
//
//                SysUser sysUser = WXShiroUtils.getSysUser();
//                if (sysUser != null) {
//                    jsonId = WXShiroUtils.getToken();
//                    map.put("jsonId", jsonId);
//                    WXLoginUtils.setWXLoginCache(jsonId, map);
//                    return AjaxResult.success("登录成功", jsonId);
//                } else {
//                    WXLoginUtils.setWXLoginCache(jsonId, map);
//                    return AjaxResult.success("登录成功", jsonId);
//                }
//            } else {
//                return new AjaxResult(AjaxResult.Type.OTHER, "请授权绑定账号", openId);
//            }
//        }
//        return AjaxResult.error("登陆失败，请重新登录", wxLogin);
//    }

    @PostMapping("/showCode")
    @ApiOperation(value = "获取登录页是否展示验证码", notes = "")
    public AjaxResult showCode() {
        JSONObject obj = new JSONObject();
        obj.put("show", false);
        obj.put("type", captchaType);
        return AjaxResult.success(obj);
    }

    //    @PostMapping("/login")
//    @ApiOperation("用户登录接口")
//    public AjaxResult ajaxLogin(String openId, String userName, String passWord, HttpServletRequest request) {//031d56ml225dt94URvml2LeZK72d56mY
//        WxLogin wxLogin = new WxLogin();
//        // 根据openId查找用户
//        WxLogin userOptional = wxLoginService.selectWxLogin(openId);
//        SysUser user = userService.selectUserByLoginName(userName);
//        // 生成一个jsonId
//        String jsonId = CharUtil.getRandomString(32);
//        Map<String, Object> map = new HashMap<>();
//        wxLogin.setOpenId(openId);
//        if (user == null) {
//            return AjaxResult.error("登录失败");
//        }
//        String s = passwordService.encryptPassword(userName, passWord, user.getSalt());
//        if (!s.equals(user.getPassword())) {
//            return AjaxResult.error("登录失败,密码错误");
//        }
//        wxLogin.setUserId(user.getUserId());
//        int i = wxLoginService.insertWxLogin(wxLogin); // 生成一个jsonId
//        map.put("user", user);
//        map.put("jsonId", jsonId);
//        WXLoginUtils.setWXLoginCache(jsonId, map);
//        return AjaxResult.success("登录成功", jsonId);
//    }
//
    @PostMapping("/showHead")
    @ApiOperation("用户登录接口")
    public AjaxResult showHead() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        return AjaxResult.success("登录头像", sysUser);
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String userName, String passWord) {
        //UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord, rememberMe);
        //Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        LoginBody loginBody = new LoginBody();
        loginBody.setUsername(userName);
        loginBody.setPassword(passWord);
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.loginWx(loginBody.getUsername(), loginBody.getPassword());

        ajax.put(Constants.TOKEN, token);

        return ajax;
    }

}

